package easymodbus4j.example3.sl651;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;

public class NettyTcpServerWithCharset {
    private final int port;

    public NettyTcpServerWithCharset(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        // 配置线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 关键修复：指定UTF-8字符集，解决中文乱码
                            pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));

                            // 自定义处理器
                            pipeline.addLast(new TcpServerHandler());
                        }
                    });

            // 绑定端口并启动
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("TCP服务器已启动，监听端口: " + port + "（支持中文）");

            // 等待服务器关闭
            future.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    // 自定义处理器
    static class TcpServerHandler extends SimpleChannelInboundHandler<String> {

        // 客户端连接成功时触发
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            String clientAddr = ctx.channel().remoteAddress().toString();
            System.out.println("客户端连接: " + clientAddr);
            // 发送中文欢迎消息
            ctx.writeAndFlush("欢迎连接到Netty服务器！请输入中文测试～\n");
        }

        // 接收客户端消息
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) {
            String clientAddr = ctx.channel().remoteAddress().toString();
            System.out.println("收到来自 " + clientAddr + " 的消息: " + msg);

            // 响应中文消息
            String response = "服务器已收到: " + msg + "（中文正常显示）\n";
            ctx.writeAndFlush(response);
        }

        // 异常处理
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            System.out.println("发生异常: " + cause.getMessage());
            ctx.close();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 启动服务器，监听8888端口
        new NettyTcpServerWithCharset(8886).start();
    }
}


